<template>
  <s-layout
    title="选择车型"
    navbar="custom"
    tabbar="/pages/index/rental"
  >
    <view class="page-container">
      <!-- 头部标题 -->
      <view class="page-title">
        <text class="title-text">选择车型</text>
      </view>

      <!-- 头部区域 - 搜索框 -->
      <view class="header-section">
        <view class="search-container">
          <s-search-block
            :data="{ placeholder: '搜索车型', borderRadius: 18 }"
            :radius="18"
            elBackground="#f5f6f8"
            :height="36"
            width="100%"
            :navbar="false"
            @click="onSearchClick"
          />
        </view>
      </view>

      <!-- 筛选栏 - 三个选项横向并列 -->
      <!-- <view class="filter-section">
        <view class="filter-item" :class="{ active: state.currentSort !== 'recommend' }" @tap="handleSort">
          <text class="filter-text">{{ state.currentSortText }}</text>
          <text class="filter-arrow">▼</text>
        </view>
        <view class="filter-item" @tap="handleBrand">
          <text class="filter-text">品牌</text>
          <text class="filter-arrow">▼</text>
        </view>
        <view class="filter-item" @tap="handleMoreFilter">
          <text class="filter-text">更多筛选</text>
          <text class="filter-arrow">▼</text>
        </view>
      </view> -->

      <!-- 主体内容区域 - 分类和车辆并列 -->
      <view class="main-content">
        <!-- 左侧分类列表 -->
        <view class="category-sidebar">
          <scroll-view scroll-y="true" class="category-scroll-view">
            <view 
              v-for="(category, index) in state.categories" 
              :key="category.id"
              class="category-item"
              :class="{ active: state.activeCategory === index }"
              @tap="selectCategory(index)"
            >
              <text class="category-name">{{ category.name }}</text>
            </view>
          </scroll-view>
        </view>

        <!-- 右侧车辆列表 -->
        <view class="car-content">
          <scroll-view scroll-y="true" class="car-list" @scrolltolower="loadMore">
            <!-- 空状态显示 -->
            <view v-if="state.carList.length === 0 && state.loadStatus !== 'loading'" class="empty-category">
              <view class="empty-content">
                <view class="empty-line"></view>
                <text class="empty-text">{{ state.categories[state.activeCategory]?.name || '暂无数据' }}</text>
                <view class="empty-line"></view>
              </view>
            </view>
            
            <!-- 车辆列表 -->
            <view 
              v-for="car in sortedCarList" 
              :key="car.id"
              class="car-item"
              @tap="selectCar(car)"
            >
              <image class="car-image" :src="car.image" mode="aspectFit" />
              <view class="car-info">
                <text class="car-name">{{ car.name }}</text>
                <view class="car-price-section">
                  <text v-if="car.price" class="car-price">{{ car.price }}</text>
                </view>
              </view>
            </view>
            
            <!-- 加载状态 -->
            <view v-if="state.loadStatus === 'loading'" class="loading-text">加载中...</view>
            <!-- <view v-if="state.loadStatus === 'noMore'" class="loading-text">没有更多了</view> -->
            <view v-if="state.loadStatus === 'error'" class="loading-text">加载失败</view>
            
            <view class="bottom-safe-area"></view>
          </scroll-view>
        </view>
      </view>
    </view>

    <!-- 排序弹窗 -->
    <view v-if="state.showSortModal" class="sort-modal-overlay" @tap="closeSortModal">
      <view class="sort-modal" @tap.stop>
        <view class="sort-header">
          <text class="sort-title">排序</text>
          <text class="sort-close" @tap="closeSortModal">✕</text>
        </view>
        <view class="sort-options">
          <view 
            class="sort-option" 
            :class="{ active: state.currentSort === 'recommend' }"
            @tap="selectSort('recommend')"
          >
            <text class="sort-option-text">推荐排序</text>
          </view>
          <view 
            class="sort-option" 
            :class="{ active: state.currentSort === 'priceAsc' }"
            @tap="selectSort('priceAsc')"
          >
            <text class="sort-option-text">价格升序</text>
          </view>
          <view 
            class="sort-option" 
            :class="{ active: state.currentSort === 'priceDesc' }"
            @tap="selectSort('priceDesc')"
          >
            <text class="sort-option-text">价格降序</text>
          </view>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { reactive, computed, onMounted } from 'vue';
import sheep from '@/sheep';
import CategoryApi from '@/sheep/api/product/category';
import SpuApi from '@/sheep/api/product/spu';

// 隐藏原生tabBar
uni.hideTabBar({
  fail: () => {},
});

const state = reactive({
  activeCategory: 0,
  showSortModal: false,
  currentSort: 'recommend',
  currentSortText: '推荐排序',
  categories: [
    { id: 0, name: '全部', type: 'all' }
  ],
  carList: [],
  loadStatus: '',
  pagination: {
    pageNo: 1,
    pageSize: 20,
    total: 0
  },
  vehicleRentalCategoryId: null, // 存储车辆租赁父分类ID
  allSubCategoryIds: [] // 存储所有子分类ID
});

// 获取分类数据
async function getCategoryList() {
  try {
    const { data } = await CategoryApi.getCategoryList();
    
    // 找到车辆租赁的一级分类
    const vehicleRentalCategory = data.find(item => item.name === '车辆租赁' && item.parentId === 0);
    
    if (vehicleRentalCategory) {
      // 存储车辆租赁父分类ID
      state.vehicleRentalCategoryId = vehicleRentalCategory.id;
      
      // 过滤出车辆租赁的二级分类
      const subCategories = data.filter(item => item.parentId === vehicleRentalCategory.id);
      
      // 存储所有子分类ID
      state.allSubCategoryIds = subCategories.map(item => item.id);
      
      // 构建分类数据，保留全部选项
      const categoryList = [
        { id: 0, name: '全部', type: 'all' },
        ...subCategories.map(item => ({
          id: item.id,
          name: item.name,
          type: item.name.toLowerCase(),
          picUrl: item.picUrl
        }))
      ];
      
      state.categories = categoryList;
      // 获取分类数据后，加载商品列表
      getCarList();
    }
  } catch (error) {
    console.error('获取分类数据失败:', error);
    // 如果API调用失败，使用默认分类
    state.categories = [
      { id: 0, name: '全部', type: 'all' }
    ];
    getCarList();
  }
}

// 获取车辆列表
async function getCarList() {
  try {
    state.loadStatus = 'loading';
    
    const selectedCategory = state.categories[state.activeCategory];
    const params = {
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
    };
    
    // 根据选中分类设置查询参数
    if (selectedCategory.type === 'all') {
      // 点击全部时，传递所有子分类ID
      if (state.allSubCategoryIds.length > 0) {
        params.categoryIds = state.allSubCategoryIds.join(',');
      }
    } else {
      // 点击具体分类时，传递单个分类ID
      params.categoryId = selectedCategory.id;
    }
    
    // 添加排序参数
    if (state.currentSort === 'priceAsc') {
      params.sortField = 'price';
      params.sortAsc = true;
    } else if (state.currentSort === 'priceDesc') {
      params.sortField = 'price';
      params.sortAsc = false;
    }
    
    const { code, data } = await SpuApi.getSpuPage(params);
    
    if (code === 0) {
      // 处理数据格式，映射到车辆列表格式
      const processedList = data.list.map(item => ({
        id: item.id,
        name: item.name,
        price: `¥${(item.price / 100).toFixed(0)}/天起`, // 价格从分转换为元
        priceValue: item.price / 100,
        image: item.picUrl,
        categoryId: item.categoryId
      }));
      
      if (state.pagination.pageNo === 1) {
        state.carList = processedList;
      } else {
        state.carList = [...state.carList, ...processedList];
      }
      
      state.pagination.total = data.total;
      state.loadStatus = state.carList.length < data.total ? 'more' : 'noMore';
    } else {
      state.loadStatus = 'error';
    }
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    state.loadStatus = 'error';
  }
}

onMounted(() => {
  getCategoryList();
});

// 根据排序方式排序车辆列表
const sortedCarList = computed(() => {
  return state.carList;
});

function selectCategory(index) {
  state.activeCategory = index;
  // 重置分页
  state.pagination.pageNo = 1;
  state.carList = [];
  // 重新加载数据
  getCarList();
}

function handleSort() {
  state.showSortModal = true;
}

function closeSortModal() {
  state.showSortModal = false;
}

function selectSort(sortType) {
  state.currentSort = sortType;
  
  switch (sortType) {
    case 'recommend':
      state.currentSortText = '推荐排序';
      break;
    case 'priceAsc':
      state.currentSortText = '价格升序';
      break;
    case 'priceDesc':
      state.currentSortText = '价格降序';
      break;
  }
  
  // 重置分页并重新加载数据
  state.pagination.pageNo = 1;
  state.carList = [];
  getCarList();
  
  closeSortModal();
}

function handleBrand() {
  console.log('品牌筛选');
}

function handleMoreFilter() {
  console.log('更多筛选');
}

function selectCar(car) {
  console.log('选择车辆:', car);
  // 跳转到租赁商品详情页
  sheep.$router.go('/pages/goods/rental', { id: car.id });
}

// 搜索框点击事件
function onSearchClick() {
  sheep.$router.go('/pages/index/search');
}

// 加载更多
function loadMore() {
  if (state.loadStatus === 'more') {
    state.pagination.pageNo++;
    getCarList();
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

/* 页面标题 */
.page-title {
  padding: 24rpx 30rpx 16rpx;
  background: #fff;
  text-align: center;
  
  .title-text {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    line-height: 1.4;
  }
}

/* 头部区域 - 搜索框 */
.header-section {
  display: flex;
  align-items: flex-start;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .search-container {
    flex: 1;
  }
}

/* 筛选栏 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-item {
    display: flex;
    align-items: center;
    flex: 1;
    justify-content: center;
    
    .filter-text {
      font-size: 28rpx;
      color: #666666;
      font-weight: 400;
      margin-right: 8rpx;
    }
    
    .filter-arrow {
      font-size: 20rpx;
      color: #999999;
    }
    
    &.active {
      .filter-text {
        color: #D4AF37;
        font-weight: 500;
      }
      
      .filter-arrow {
        color: #D4AF37;
      }
    }
  }
}

/* 主体内容区域 - 分类和车辆并列 */
.main-content {
  flex: 1;
  display: flex;
  
  /* 左侧分类列表 */
  .category-sidebar {
    width: 200rpx;
    background: #f6f6f6;
    border-right: 1rpx solid #e5e5e5;
    
    .category-scroll-view {
      height: 100%;
    }
    
    .category-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 32rpx 20rpx;
      border-bottom: 1rpx solid #e5e5e5;
      position: relative;
      
      .category-name {
        font-size: 26rpx;
        color: #666666;
        text-align: center;
        line-height: 1.4;
      }
      
      &.active {
        background: #fff;
        
        .category-name {
          color: #D4AF37;
          font-weight: 500;
        }
        
        &::after {
          content: '';
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 6rpx;
          height: 40rpx;
          background: #D4AF37;
          border-radius: 3rpx 0 0 3rpx;
        }
      }
    }
  }
  
  /* 右侧车辆列表 */
  .car-content {
    flex: 1;
    background: #fff;
    
    .car-list {
      height: 100%;
      
      /* 空状态样式 */
      .empty-category {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 400rpx;
        
        .empty-content {
          display: flex;
          align-items: center;
          justify-content: center;
          
          .empty-line {
            width: 30rpx;
            height: 2rpx;
            background: #e5e5e5;
          }
          
          .empty-text {
            font-size: 28rpx;
            color: #999;
            margin: 0 20rpx;
          }
        }
      }
      
      .car-item {
        display: flex;
        align-items: center;
        padding: 32rpx 30rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:active {
          background: #f8f8f8;
        }
        
        .car-image {
          width: 160rpx;
          height: 100rpx;
          margin-right: 24rpx;
          border-radius: 8rpx;
        }
        
        .car-info {
          flex: 1;
          
          .car-name {
            font-size: 32rpx;
            color: #333;
            font-weight: 500;
            line-height: 1.4;
            margin-bottom: 16rpx;
          }
          
          .car-price-section {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12rpx;
            
            .car-price {
              font-size: 28rpx;
              color: #D4AF37;
              font-weight: 500;
            }
            
            .car-dots {
              display: flex;
              gap: 8rpx;
              
              .color-dot {
                width: 16rpx;
                height: 16rpx;
                border-radius: 50%;
                border: 1rpx solid #eee;
              }
            }
          }
          
          .car-available-section {
            display: none; /* 隐藏不需要的可选信息 */
          }
        }
        
        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
}

.bottom-safe-area {
  height: 120rpx;
}

/* 排序弹窗样式 */
.sort-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 120rpx;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.sort-modal {
  width: 100%;
  background: #fff;
  border-radius: 0;
  padding-bottom: 0;
  box-shadow: none;
  border-top: 1rpx solid #f0f0f0;
  pointer-events: auto;
  margin-bottom: -29rpx;
}

.sort-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .sort-title {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
  }
  
  .sort-close {
    font-size: 32rpx;
    color: #999;
    padding: 10rpx;
  }
}

.sort-options {
  padding: 40rpx 30rpx 40rpx;
  display: flex;
  gap: 20rpx;
}

.sort-option {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 20rpx;
  border-radius: 50rpx;
  background: #f8f8f8;
  flex: 1;
  
  &.active {
    background: #8B7355;
    
    .sort-option-text {
      color: #fff;
    }
  }
  
  .sort-option-text {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    text-align: center;
    width: 100%;
  }
}
</style>













